export default {
  methods: {
    // 模板下载
    handleDownloadTemplate() {
      const params = {
        access_token: this.token,
        scope: this.websiteId
      }
      this.downloadTemplate(params)
        .then(() => {
          console.log('下载完成！')
        })
        .catch(err => {
          console.error('/v1/datac/app/importData/getTemplate:::::::', err)
        })
    },
    handleSelect(node) {
      if (node.data.text) {
        if (node.parent) {
          this.handleSelect(node.parent)
        }
        this.cNode.push(node.data.text)
      }
    },
    handleNodeEdit(node) {
      this.cNode = []
      this.handleSelect(node)
      this.cNodeStr = this.cNode.join('\\')
      if (node) {
        this.currentNode = node
        this.store._searchParams = {}
        this.store._searchParams['q_' + this.idKey] = node.data[this.nodeIdKey]
        this.$refs.table.load(1, this.store.limit)
      }
      this.renderTreeCheckCallback(node)
    },
    handleAdd() {
      if (this.q_deptId === '') {
        this.$message({
          type: 'info',
          message: '该节点为虚拟节点不可新增，请选择子部门'
        })
      } else {
        this.dialogType = this.formPanel.add.type
        this.$nextTick(() => {
          // 清空表单内容避免遗留上次新增内容
          this.$refs.addForm && this.$refs.addForm.resetFields()
          this.formPanel.add.model = this.addModelInitData
          this.formPanel.add.model.groupId = this.groupId
          this.formPanel.add.model.deptId = this.store._searchParams.q_deptId
        })
      }
    },
    handleTreeSubSelect(val) {
      val && (this.groupId = val)
      !val && (this.groupId = '')
    },
    handleCurrentChange(row) {
      this.dialogType = this.formPanel.look.type
      this.check({
        userId: row.userId
      }).then(({ success, data }) => {
        if (success) {
          this.$refs.lookForm && this.$refs.lookForm.resetFields()
          Object.keys(data).forEach(key => {
            for (key in this.formPanel.look.model) {
              if (key === 'time') {
                if (!!data.authStartDate && !!data.authEndDate) {
                  const timeArr = []
                  timeArr[0] = data.authStartDate
                  timeArr[1] = data.authEndDate
                  this.$set(this.formPanel.look.model, key, timeArr)
                }
              } else if (key === 'groupName') {
                this.$set(this.formPanel.look.model, key, row[key])
              } else if (key === 'deptName') {
                this.$set(this.formPanel.look.model, key, row[key])
              } else {
                this.$set(this.formPanel.look.model, key, data[key])
              }
            }
          })
        }
      })
    },
    handleImportPeople() {
      if (this.q_deptId === '') {
        this.$message({
          type: 'info',
          message: '该节点为虚拟节点不可导入，请选择子部门'
        })
      } else {
        this.dialogType = 'IMPORTPEOPLE'
      }
    },
    handleImportPeopleSubmit() {
      const params = {}
      params.deptId = this.q_deptId
      params.userIds = this.$refs.ImportPeople.handleReturnSelectedList()
        .map(item => {
          return item.userId
        })
        .join(',')
      this.importPeople(params)
        .then(({ success, message }) => {
          if (success) {
            this.$message({
              type: 'success',
              message: message
            })
            this.$refs.table.load(1)
            this.dialogType = ''
          } else {
            this.$message({
              type: 'error',
              message: message
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    handleImportPeopleCancel() {
      this.dialogType = ''
    },
    handleTable() {
      if (this.projectId) {
        this.columns = this.columnsProject
        this.toolPanelBtnList = this.toolPanelBtnListProject
        this.formPanel.add.fields = this.addProjectFields
        this.formPanel.edit.fields = this.editProjectFields
        this.formPanel.look.fields = this.lookProjectFields
      } else {
        this.columns =
          this.systemType === '1'
            ? this.columnsPingtaiWithoutProject
            : this.columnsPingtai
        this.toolPanelBtnList = this.toolPanelBtnListPingtai
      }
    },
    getData({ page, limit }) {
      this.store && (this.store._searchParams.q_groupId = this.groupId)
      this.store.read({
        start: page,
        limit: limit
      })
    },
    renderTreeCheckCallback(node) {
      this.currentSelectedDeptmentName = node.data.text
      this.q_deptId = node.data.id
    },
    handleEdit(row) {
      const params = {}
      params['userId'] = row['userId']
      this.check(params).then(({ success, data }) => {
        if (success) {
          Object.assign(this.formPanel.edit.model, this.editModelInitData)
          Object.keys(data).forEach(key => {
            for (key in this.formPanel.edit.model) {
              if (key === 'time') {
                if (!!data.authStartDate && !!data.authEndDate) {
                  const timeArr = []
                  timeArr[0] = data.authStartDate
                  timeArr[1] = data.authEndDate
                  this.$set(this.formPanel.edit.model, key, timeArr)
                }
              } else {
                this.$set(this.formPanel.edit.model, key, data[key])
              }
            }
          })
          this.dialogType = this.formPanel.edit.type
        }
      })
    },
    handleDel(row, str, deptId) {
      return this.$confirm(
        str === '移除'
          ? '确认要将用户从该站点移除么?'
          : '此操作不能回退，确认要删除您选中的数据么?',
        '提示',
        {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        }
      )
        .then(() => {
          const params = {}
          params[this.delIdKey] = row[this.delIdKey]
          if (str === '移除') {
            Object.assign(params, {
              deptId: deptId
            })
          }
          return this.del(params)
        })
        .then(({ success, message }) => {
          this.$message({
            type: success ? 'success' : 'error',
            message: success ? str + '用户成功！' : message
          })
          if (success) {
            this.$refs.table.load(1)
            // 删除后 刷新本地 tree
          }
          setTimeout(() => {
            document.activeElement.blur()
          }, 300)
        })
        .catch(error => {
          setTimeout(() => {
            document.activeElement.blur()
          }, 300)
          this.$message({
            type: 'info',
            message:
              error === 'cancel'
                ? str === '移除'
                  ? '已取消移除'
                  : '已取消删除'
                : error
          })
          return Promise.reject(error)
        })
    },
    handleRemove(row) {
      this.handleDel(row, '移除', row.deptId)
    },
    handleDelete(row) {
      this.handleDel(row, '删除', '')
    },
    handleDelGroup() {
      if (this.selectedList.length === 0) {
        this.$message({
          type: 'info',
          message: '没有要删除的数据'
        })
        return false
      }
      const funIds = this.selectedList
        .map(item => {
          return item['userId']
        })
        .join(',')
      this.$confirm('此操作不能回退，确认要删除您选中的数据么?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        callback: (action, instance) => {
          instance.focusAfterClosed && instance.focusAfterClosed.blur()
          if (action === 'confirm') {
            const params = {}
            params['userIds'] = funIds
            this.delList(params)
              .then(({ success, message }) => {
                if (success) {
                  this.$refs.table.load(1)
                  this.$message({
                    type: 'success',
                    message: message
                  })
                  // 删除后 刷新本地 table
                  this.$refs.table.load(1)
                } else {
                  this.$message({
                    type: 'error',
                    message: message
                  })
                }
              })
              .catch(error => {
                console.log(error)
              })
            this.$refs.table.clearSelection()
          } else {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          }
        }
      })
    },
    handleSubmitAndAdd() {
      this.$refs.addForm.model.authStartDate = ''
      this.$refs.addForm.model.authEndDate = ''
      if (this.projectId && !!this.$refs.addForm.model.time) {
        this.$refs.addForm.model.authStartDate = this.$refs.addForm.model.time[0]
        this.$refs.addForm.model.authEndDate = this.$refs.addForm.model.time[1]
        delete this.$refs.addForm.model.time
      }
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.add(this.formPanel.add.model).then(({ success, message }) => {
            if (success) {
              this.$refs.table.load(1)
              this.$message({
                type: 'success',
                message: message
              })
              const gId = this.$refs.addForm.model.groupId
              const dId = this.$refs.addForm.model.deptId
              this.$refs.addForm && this.$refs.addForm.resetFields()
              this.formPanel.add.model.groupId = gId
              this.formPanel.add.model.deptId = dId
            } else {
              this.$message({
                type: 'error',
                message: message
              })
            }
          })
        }
      })
    },
    handleAddSubmit() {
      this.$refs.addForm.model.authStartDate = ''
      this.$refs.addForm.model.authEndDate = ''
      if (this.projectId && !!this.$refs.addForm.model.time) {
        this.$refs.addForm.model.authStartDate = this.$refs.addForm.model.time[0]
        this.$refs.addForm.model.authEndDate = this.$refs.addForm.model.time[1]
        delete this.$refs.addForm.model.time
      }
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.add(this.formPanel.add.model)
            .then(({ success, message }) => {
              if (success) {
                this.$refs.table.load(1)
                this.dialogType = ''
                this.$message({
                  type: 'success',
                  message: message
                })
              } else {
                this.$message({
                  type: 'error',
                  message: message
                })
              }
            })
            .catch(error => {
              console.log(error)
            })
        }
      })
    },
    handleEditSubmit() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          if (this.projectId && !!this.$refs.editForm.model.time) {
            this.$refs.editForm.model.authStartDate = this.$refs.editForm.model.time[0]
            this.$refs.editForm.model.authEndDate = this.$refs.editForm.model.time[1]
          }
          this.update(this.formPanel.edit.model).then(
            ({ success, message }) => {
              if (success) {
                this.$refs.table.load()
                this.dialogType = ''
                this.$message({
                  type: 'success',
                  message: message
                })
              } else {
                this.$message({
                  type: 'error',
                  message: message
                })
              }
            }
          )
        }
      })
    },
    handleRoleFenpei(model) {
      this.userId = model.userId
      this.userName = model.userName
      this.dialogType = 'ROLEFENPEI'
      this.roleFenpeiLoading = true
    },
    handlePasswordReset(model) {
      this.$confirm('确定重置密码?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        callback: (action, instance) => {
          instance.focusAfterClosed && instance.focusAfterClosed.blur()
          if (action === 'confirm') {
            this.resetPassword({
              userId: model.userId
            })
              .then(({ success }) => {
                if (success) {
                  this.$message({
                    type: 'success',
                    message: '重置密码成功，重置后密码为6个8!'
                  })
                } else {
                  this.$message({
                    type: 'error',
                    message: '重置密码失败!'
                  })
                }
              })
              .catch(error => {
                console.log(error)
              })
          } else {
            this.$message({
              type: 'info',
              message: '已取消重置密码'
            })
          }
        }
      })
    },
    handleTreeEmpty() {
      this.data = []
    },
    handleDataFenpei(model) {
      this.userId = model.userId
      this.userName = model.userName
      this.dialogType = 'DATAFENPEI'
      this.$nextTick(() => {
        this.$refs.DataFenpei.reloadTree()
      })
    },
    handleDataFenpeiSubmit() {
      const params = {}
      params.userId = this.userId
      params.groupIds = this.$refs.DataFenpei.getCheckedList()
        .map(item => {
          return item
        })
        .join(',')
      this.dataFenpei(params)
        .then(({ success, message }) => {
          if (success) {
            this.$message({
              type: 'success',
              message: message
            })
            this.dialogType = ''
          } else {
            this.$message({
              type: 'error',
              message: message
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    handleDataFenpeiCancel() {
      this.$refs.DataFenpei.$refs.tree.emptyChecked()
      this.dialogType = ''
    },
    handleRoleFenpeiSubmit() {
      const params = {}
      params.roleIds = this.$refs.RoleFenpei.handleReturnSelectedList()
        .map(item => {
          return item.roleId
        })
        .join(',')
      params.ownRoles = this.$refs.RoleFenpei.handleReturnSelectedList()
        .map(item => {
          return item.roleName
        })
        .join(',')
      params.userId = this.userId
      this.roleFenpei(params)
        .then(({ success, message }) => {
          if (success) {
            this.$message({
              type: 'success',
              message: message
            })
            this.dialogType = ''
            this.$refs.table.load(1)
          } else {
            this.$message({
              type: 'error',
              message: message
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    handleRoleFenpeiCancel() {
      this.$refs.RoleFenpei.handleEmptySelectedList()
      this.dialogType = ''
    },
    handleInputClick(ev, val) {
      const params = {}
      params.q_deptId = this.q_deptId
      params.q_name = val
      this.store._searchParams = params
      this.$refs.table.load(1, this.store.limit)
    }
  }
}
